package cn.rengy.isql.lang;

import cn.rengy.util._StrUtil;

public class SortUtil {

    public static String getOrderSql(String orderBy,String ascOrDesc) {
        StringBuilder orderSql = new StringBuilder();
        if (orderBy==null||orderBy.length()==0){
            return "";
        }
        orderBy= _StrUtil.camelCase2Underscore(orderBy);
        String alias_="";
//        if (alias!=null&&alias.length()>0) {
//            alias_ = alias + ".";
//        }
        orderSql.append(" order by ");
        if (ascOrDesc!=null&&ascOrDesc.length()>0) {//不为空
            String[] orders = orderBy.split(",");
            String[] sorts = ascOrDesc.split(",");
            if (orders.length == sorts.length) {// 长度相等
                for (int i = 1; i <= orders.length; i++) {
                    orderSql.append(alias_).append(orders[i - 1]).append(" ").append(
                            sorts[i - 1]);
                    if (i < orders.length) {
                        orderSql.append(",");
                    }
                }
            } else {// 长度不相等
                for (int i = 1; i <= orders.length; i++) {
                    orderSql.append(alias_).append(orders[i - 1]).append(" ").append(
                            sorts[0]);
                    if (i < orders.length) {
                        orderSql.append(",");
                    }
                }
            }
        } else {// order 为空
            String [] orders  = orderBy.split(",");
            for (int i = 1; i <= orders.length; i++) {
                orderSql.append(alias_).append(orders[i - 1]);
                if (i < orders.length) {
                    orderSql.append(",");
                }
            }
        }
        return orderSql.toString();
    }
}
